package utils

import (
	"errors"
	"strings"
	"time"

	"github.com/golang-jwt/jwt/v4"
	uuid "github.com/satori/go.uuid"
)

type MyClaim struct {
	Name  string
	Email string
	jwt.RegisteredClaims
}

func GenerateToken(username, email, secretKey string, AccessExpire int64) (string, error) {
	newCliam := MyClaim{
		Name:  username,
		Email: email,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Unix(time.Now().Unix()+AccessExpire, 0)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			ID:        strings.ReplaceAll(uuid.NewV4().String(), "-", ""),
		},
	}

	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, newCliam).SignedString([]byte(secretKey))
	return token, err
}

func ParseToken(tokenStr, secretKey string) (*MyClaim, error) {
	token, err := jwt.ParseWithClaims(tokenStr, &MyClaim{}, func(t *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return nil, err
	}
	if !token.Valid {
		return nil, errors.New("claim invalid")
	}

	claim := token.Claims.(*MyClaim)
	return claim, nil
}
